using System;
using System.Diagnostics;
using System.Reflection;
using PostSharp.Extensibility;
using PostSharp.Laos;
using PostSharp.Reflection;

namespace AOP
{
    [MulticastAttributeUsage(MulticastTargets.Class | MulticastTargets.Struct | MulticastTargets.Assembly)]
    [Serializable]
    public sealed class ExternalAspectImplementation : IExternalAspectImplementation
    {
        public void ImplementAspect(object targetElement, IObjectConstruction aspectData,
                                    LaosReflectionAspectCollection collection)
        {
            // Get the target type.
            var targetType = (Type)targetElement;
            // On the type, add a Composition aspect to implement the INotifyPropertyChanged interface. 
            //collection.AddAspect(targetType, new AddNotifyPropertyChangedInterfaceSubAspect());
            // Add a OnMethodBoundaryAspect on each writable non-static property. 
            foreach (PropertyInfo property in targetType.GetProperties())
            {
                if (property.DeclaringType.AssemblyQualifiedName == targetType.AssemblyQualifiedName
                        && property.CanWrite)
                {
                    MethodInfo method = property.GetSetMethod(true);
                    if (method != null && !method.IsStatic)
                    {
                        collection.AddAspectConstruction(method,
                                                         new ObjectConstruction("AOP.OnPropertySetSubAspect, BusinessFramework.SL",
                                                                                property.Name), null);
                    }
                }
            }
        }
    }
}